package com.qk.management.aop;


import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.service.OperateLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author:Shuna
 * @Date: 2025/10/17 11:13
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class LogRecordAspect {

    @Autowired
    private OperateLogService operateLogService;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {

    }

    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) {

        Object returnValue = null;
        try {
            long start = System.currentTimeMillis();
            returnValue = pjp.proceed();
            long end = System.currentTimeMillis();
            Integer userId = CurrentUserContextHolders.get();
            String methodName = pjp.getSignature().getName();
            String className = pjp.getTarget().getClass().getName();
            String methodParams = JSONUtil.toJsonStr(pjp.getArgs());
            String returnValueStr = JSONUtil.toJsonStr(returnValue);
            OperateLog operateLog = OperateLog.builder()
                    .costTime(end - start)
                    .operateUserId(userId)
                    .operateTime(LocalDateTime.now())
                    .methodName(methodName)
                    .className(className)
                    .methodParams(methodParams)
                    .returnValue(returnValueStr)
                    .build();
            try {
                operateLogService.save(operateLog);
            } catch (Exception e) {
                CommonException.throwCommonException(ParamEnum.OPERATION_FAILED);
            }
        } catch (Throwable e) {
            returnValue = Result.error(ParamEnum.OPERATION_FAILED.getMsg());
            log.error("操作失败{}", e.getMessage());
        }

        return returnValue;
    }


}
